package com.wh.connection_pool;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
/**
 * 
 *  Class Name: ConnectionPoolManager.java 
 *  懒汉式 加载
 *  Description: 代码地址：http://greemranqq.iteye.com/blog/1969273
 *  @author wanghao  DateTime 2017年3月2日 下午5:31:47 
 *  @company hongbo
 *  @email 1228675455@qq.com
 */
public class ConnectionPoolManager {

	private static ConnectionPoolManager connectionPoolManager;
	
	private ConcurrentHashMap<String, ConnectionPool> pools = new ConcurrentHashMap<String, ConnectionPool>();
	
	private ConnectionPoolManager() {
		
	}
	
	public static ConnectionPoolManager getInstance() {
		return connectionPoolManager == null ? connectionPoolManager : new ConnectionPoolManager(); 
	}
	
	/**
	 * 
	 *  Description:初始化所有连接池
	 *  @author wanghao  DateTime 2017年3月3日 上午11:02:47
	 */
	public void init() {
		for(Iterator<DBbean> iterator = DBInitInfo.beans.iterator(); iterator.hasNext();) {
			DBbean bbean = iterator.next();
			ConnectionPool connectionPool = new ConnectionPoolImpl(bbean);
			if(connectionPool != null) {
				pools.put(bbean.getPoolName(), connectionPool);
				System.out.println("info:Init connection successed ->" + bbean.getPoolName());
			}
		}
	}
	
	/**
	 * 
	 *  Description:	根据连接池的名字，获取连接 
	 *  @author wanghao  DateTime 2017年3月3日 下午1:37:51
	 *  @param poolName
	 *  @return
	 */
	public Connection getConnection(String poolName) {
		Connection connection = null;
		if(pools.size() > 0 && pools.containsKey(poolName)) {
			connection = pools.get(poolName).getConnection();
		} else{  
            System.out.println("Error:Can't find this connecion pool ->"+poolName);  
        }  
        return connection;
	}
	
	/**
	 * 
	 *  Description:关闭回收连接
	 *  @author wanghao  DateTime 2017年3月3日 下午4:12:32
	 *  @param poolName
	 *  @param conn
	 */
	public void close(String poolName, Connection conn) {
		ConnectionPool connectionPool = getPool(poolName);
		if(connectionPool != null) {
			try {
				connectionPool.releaseConn(conn);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 
	 *  Description:获得连接池
	 *  @author wanghao  DateTime 2017年3月3日 下午4:21:58
	 *  @param poolName
	 *  @return
	 */
	public ConnectionPool getPool(String poolName) {
		ConnectionPool connectionPool = null;
		if(pools.size() > 0) {
			connectionPool = pools.get(poolName);
		}
		return connectionPool;
	}
}
